#!/usr/bin/env python2.5
#coding: utf8

#Author: Gang Li
#Date: 2010-04-10 18:20

from ihooks import ModuleLoader, ModuleImporter
from urllib2 import urlopen, HTTPError
from urlparse import urljoin
import tempfile
import os

class MRModuleLoader(ModuleLoader):
    def set_find_module_ex(self, base):
        self.base = base

    def find_module(self, name, path=None):
        stub=ModuleLoader.find_module(self, name, path)
        
        print "find module",name
        
        if stub:
            print "module :", name, stub
            return stub
        if path:
            return

        url=urljoin(self.base, name+'.py')
        try:
            file = urlopen(url)
            name=tempfile.mktemp()
            stream=open(name, 'wb')
            stream.write(file.read())
            stream.close()
            file.close()

            file=open(name, 'r')
            print "module :", url
            return file, url, ('.py', 'r', 1)
        except HTTPError, e:
            print e
            return None

class MRImporter(ModuleImporter):
    def __init__(self, base):
        hooks, verbose=(None, 1)
        loader=MRModuleLoader(hooks, verbose)
        loader.set_find_module_ex(base)
        ModuleImporter.__init__(self, loader, verbose)

if __name__=="__main__":
    MRImporter("http://localhost:2010/test/t.py").install()
    import t